"use client"

import type React from "react"
import { createContext, useContext, useState, useEffect } from "react"
import type { AuthContextType, AuthUser, User } from "./types"
import { mockUsers, getUserRoles, getUserPermissions } from "./mock-data"

const AuthContext = createContext<AuthContextType | undefined>(undefined)

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [user, setUser] = useState<AuthUser | null>(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    // Check for existing session
    const savedUser = localStorage.getItem("rbac-user")
    if (savedUser) {
      try {
        const userData = JSON.parse(savedUser)
        const fullUser = mockUsers.find((u) => u.id === userData.id)
        if (fullUser) {
          setUser(createAuthUser(fullUser))
        }
      } catch (error) {
        console.error("Failed to parse saved user:", error)
        localStorage.removeItem("rbac-user")
      }
    }
    setIsLoading(false)
  }, [])

  const createAuthUser = (userData: User): AuthUser => {
    const roles = getUserRoles(userData)
    const permissions = getUserPermissions(userData)

    return {
      id: userData.id,
      email: userData.email,
      name: userData.name,
      avatar: userData.avatar,
      roles,
      permissions,
    }
  }

  const login = async (email: string, password: string): Promise<boolean> => {
    setIsLoading(true)

    // Simulate API call delay
    await new Promise((resolve) => setTimeout(resolve, 1000))

    // Mock authentication - in real app, this would call your API
    const userData = mockUsers.find((u) => u.email === email && u.status === "active")

    if (userData && password === "password") {
      // Mock password check
      const authUser = createAuthUser(userData)
      setUser(authUser)
      localStorage.setItem("rbac-user", JSON.stringify({ id: userData.id }))
      setIsLoading(false)
      return true
    }

    setIsLoading(false)
    return false
  }

  const logout = () => {
    setUser(null)
    localStorage.removeItem("rbac-user")
  }

  const hasPermission = (resource: string, action: string): boolean => {
    if (!user) return false
    return user.permissions.some((perm) => perm.resource === resource && perm.action === action)
  }

  const hasRole = (roleName: string): boolean => {
    if (!user) return false
    return user.roles.some((role) => role.name === roleName)
  }

  const value: AuthContextType = {
    user,
    login,
    logout,
    hasPermission,
    hasRole,
    isLoading,
  }

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}

export function useAuth() {
  const context = useContext(AuthContext)
  if (context === undefined) {
    throw new Error("useAuth must be used within an AuthProvider")
  }
  return context
}
